#include <iostream>

#include "netclient.h"
#include <thread>

int main(int argc, char* argv[])
{
    typedef boost::asio::ip::tcp::resolver ResolverType;

    if (argc != 3)
    {
        std::cerr << "Usage: chat_client <host> <port>\n";
        return 1;
    }

    try
    {

        ResolverType resolver(NetService::IOService().getIOService());
        ResolverType::query query(argv[1], argv[2]);
        ResolverType::iterator iterator = resolver.resolve(query);

        NetClient l_client(iterator);

        std::cout << "Create a new client for host " <<argv[1]<< " @ " << argv[2] << std::endl;

        std::thread connection_thread(NetService::run);

    char line[NetChatMsg::max_body_length + 1];
    while (std::cin.getline(line, NetChatMsg::max_body_length + 1))
    {
      NetChatMsg msg;
      msg.body_length(std::strlen(line));
      std::memcpy(msg.body(), line, msg.body_length());
      msg.encode_header();
      l_client.write(msg);
    }

    l_client.close();
    connection_thread.join();
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
    }

  return 0;
}
